import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'

interface UserState {
  loading: boolean
  error: null | unknown
  token: string | null
}

// 初始化数据
const initialState: UserState = {
  loading: false,
  error: null,
  token: null 
}

export const signIn = createAsyncThunk(
  "user/signIn",
  async (paramaters: {
    email: string,
    password: string
  }) => {
       const { data: {token} } = await axios.post('https://mock.mengxuegu.com/mock/61c70e2ebba8817f8a413580/tourism_website/auth/login', {
         email: paramaters.email,
         password: paramaters.password
       })
       console.log("详情", token)
      //  thunkAPI.dispatch(productDetailSlice.actions.fetchSuccess(data))
    //  } catch (error) {
      //  let err = error
      //  thunkAPI.dispatch(productDetailSlice.actions.fetchFail(err))
    //  }

      return token
  }
)

export const userSlice = createSlice({
  name: 'user', // 命名空间名称
  initialState, // 初始化数据
  reducers: {
    logOut: (state) => {
      state.loading = false
      state.token = null
      state.error = null
    }
  }, // 这里的reducer是把action和reducer捆绑在了一起.所以不需要在单独定义action,这里的reducer是个对象
  extraReducers: {
    [signIn.pending.type]: (state) => {
      // 原始写法
      // return { ...state, loading: true }
      state.loading = true  // immer
    },
    // reducer中已经提前定义好了action的参数
    // 请求成功
    [signIn.fulfilled.type]: (state, action) => {
      state.loading = false
      state.token = action.payload
      state.error = null
    },
    // 请求失败
    [signIn.rejected.type]: (state, action: PayloadAction<unknown | null>) => {
      state.loading = false
      state.error = action.payload
    }
  }
})